﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web.Mvc;
using EzDesk.Apps.Model.ProjectModule;
using EzDesk.Utility.Log;
using EzDesk.Utility.ServiceStatusInfo;

using EzDesk.Utility.Web.Extensions;

namespace EzDesk.ServiceHost.Controllers
{
    public partial class ProjectController : EzDeskAppController
    {

        #region Page Methods

        public ActionResult ProjectTasks(Guid id)
        {
            LogEx.TRACE("ProjectTask","start get project tasks...");
            dynamic model = new ExpandoObject();
            
            model.ProjectId = id;
            LogEx.TRACE("ProjectTask", "end get project tasks...");
            return View(model);
        }

        #endregion

        #region Ajax Methods
        /// <summary>
        /// 獲得項目Tasks
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetTasksInProject(Guid projectId)
        {
            var modelList = new List<object> { };
            Action<Task, int> recursiveTaskTree = null;
            recursiveTaskTree = (task, deep) =>
            {
                //根据层级添加前置空格
                var preStr = deep == 0 ? "" : Enumerable.Repeat("&nbsp;&nbsp;", deep).Aggregate((a, b) => a + b);
                modelList.Add(new
                {
                    Id = task.Id.ToString(),
                    Name = preStr + task.Name
                });
                task.ChildTasks.ToList().ForEach(t => recursiveTaskTree(t, deep + 1));
            };

            var tasks = ProjectService.GetPorjectTasks(projectId).Result.ToList();
            tasks.ForEach(t => recursiveTaskTree(t, 0));
            return Json(modelList, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 獲取Task的 workItems
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetWorkitemsInTask(Guid taskId)
        {
            var workitems = ProjectService.GetTaskWorkitems(taskId).Result.ToList();
            foreach (var workitem in workitems)
            {
                workitem.OwnerName = workitem.OwnerId.HasValue ? _coreAppService.GetSimpleUserById(workitem.OwnerId.Value).Name : " - ";
                workitem.CreatorName = _coreAppService.GetSimpleUserById(workitem.CreatorId).Name;
            }

            workitems = workitems
                .OrderByDescending(w => w.StatusValue)
                .OrderByDescending(w => w.CreateOn)
                .ToList();

            return Json(workitems, JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        public JsonResult AddNewTask(Guid projectId, string taskStr)
        {
            var task = WebJsonExtension.FromJson<Task>(taskStr);
            var statusInfo = ProjectService.CreateTask(task, CurrentUserId);

            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "添加项目计划成功";
            }
            return Json(statusInfo);
        }


        [HttpPost]
        public JsonResult UpdateTask(string taskStr,bool? moveChild = false)
        {
            var task = WebJsonExtension.FromJson<Task>(taskStr);

            var statusInfo = ProjectService.UpdateTask(task,moveChild, CurrentUserId);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "更新项目计划成功";
            }

            return Json(statusInfo);
        }


        /// <summary>
        /// 刪除Task 
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteTask(Guid taskId)
        {
            var statusInfo = ProjectService.DeleteTask(taskId, CurrentUserId);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "删除项目计划成功";
            }

            return Json(statusInfo);
        }

        [HttpPost]
        public JsonResult CreateTaskTemplate(string taskTemplateStr)
        {
            var taskTemplate = WebJsonExtension.FromJson<TaskTemplate>(taskTemplateStr);
            var statusInfo = ProjectService.CreateTaskTemplate(taskTemplate);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "项目模板创建成功";
            }
            return Json(statusInfo);
        }

        [HttpPost]
        public JsonResult CreateTaskWithTemplate(Guid projectid,Guid? parentTaskId,Guid taskTemplateId)
        {
            var statusInfo = ProjectService.CreateTaskWithTemplate(projectid,parentTaskId,taskTemplateId,CurrentUserId);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "计划创建成功";
            }
            return Json(statusInfo);
        }

        [HttpGet]
        public JsonResult GetTaskTemplateList()
        {
            var statusInfo = ProjectService.GetTaskTemplateList();
            if (statusInfo.Status == ServiceStatus.Success)
            {
                return Json(statusInfo.Result);
            }
            return Json("[]");
        }

        [HttpPost]
        public JsonResult RemoveTaskTemplate(Guid id)
        {
            var statusInfo = ProjectService.RemoveTaskTemplate(id);
            return Json(statusInfo);
        }


        public ActionResult _taskTemplates()
        {
            return View();
        }

        #endregion

        #region pravite methods

        #endregion
    }
}
